package com.lancoo.answer.ui.paper;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.gson.Gson;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.NoConfirmDialogHelper;
import com.lancoo.answer.helper.answer.FillAnswerDialog;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ExamViewBean;
import com.lancoo.answer.model.bean.ImgAnswerCallBackBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.model.entity.IndexBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.model.entity.TaskOperateBean;
import com.lancoo.answer.model.eventBean.AnswerSheetEventBean;
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean;
import com.lancoo.answer.model.eventBean.KeyBoardEventBean;
import com.lancoo.answer.ui.answerSheet.AnswerSheetDialog;
import com.lancoo.answer.ui.ques.NoSpliteLayoutFragment;
import com.lancoo.answer.ui.ques.WaitToDockFragment;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.util.paperUtils.FragmentCommunicationUtils;
import com.lancoo.answer.util.paperUtils.FragmentLoadUtils;
import com.lancoo.answer.util.paperUtils.PaperDataUtils;
import com.lancoo.answer.widget.ViewPagerContainer;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import kotlin.Triple;

/**
 * Created by pengmi on 2021/11/30 14:54
 * Description:整份试题paperFragment
 */
public class PaperFragment extends Fragment implements ViewTreeObserver.OnGlobalLayoutListener{

    private static final String TAG = "PaperFragment";
    private ViewPager2 viewPager2;
    private List<TaskOperateBean> taskOperateBeanList;
    private int currentTopicIndex;
    private final Map<String, Integer> queseIndexMap=new HashMap<>();
    private long subTime;
    private int answerSheetScrollY=0;
    private int lastTypeIndex,lastQuesIndex,lastChildIndex,lastItemIndex;
    private View convertView;
    private int rootViewVisibleHeight;
    private ViewPagerContainer viewpagerContainer;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        convertView = inflater.inflate(R.layout.ev_fragment_paper_test, container, false);
        return convertView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData(view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        if(convertView!=null){
            convertView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void initData(final View view){
        SoftKeyBoardListener();
        taskOperateBeanList=new ArrayList<>();

        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    queseIndexMap.clear();
                    PaperDataUtils.loadPaperData(taskOperateBeanList,queseIndexMap);
                    if(DpUtils.isApkInDebug(getContext())){
                        PaperDataUtils.zuobi();//作弊作答
                    }
                    emitter.onNext("");
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(s -> initView(view), throwable -> {});
    }


    private void initView(View view){
        if(ConstantBean.Companion.getTaskControlBean()==null){
            return;
        }
        viewPager2 = view.findViewById(R.id.viewpager2);
        viewpagerContainer = view.findViewById(R.id.viewpagerContainer);
        viewpagerContainer.setListener(() -> {
            boolean isAuto=ConstantBean.Companion.getTaskControlBean().getIsAutoShowSubmitBtn()==1;
            if(currentTopicIndex==taskOperateBeanList.size()-1&&isAuto){
                if(ConstantBean.getTaskState()== TaskState.TRAINING){
                    TaskOperateBean taskOperateBean = taskOperateBeanList.get(currentTopicIndex);
                    Ques quesBean = taskOperateBean.getQuesBean();
                    List<Child> childList =quesBean.getChildList();
                    Triple<Integer, Integer, Integer> currentIndex = getCurrentIndex();
                    if(childList!=null&&childList.size()-1==currentIndex.getThird()){
                        //并且需要处于当前后一个type的最后一个ques
                        if(ConstantBean.Companion.getConstantExamBean()==null){
                            return;
                        }
                        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
                        if(typeList==null){
                            return;
                        }
                        Type type = typeList.get(typeList.size() - 1);
                        if(type==null||type.getQuesList()==null){
                            return;
                        }
                        Ques ques = type.getQuesList().get(type.getQuesList().size()-1);
                        if(TextUtils.equals(ques.getQuesID(),quesBean.getQuesID())){
                            showAnswerSheetDialog();
                        }
                    }
                }
            }
        });
        viewPager2.setAdapter(new FragmentStateAdapter(PaperFragment.this) {

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                TaskOperateBean taskOperateBean = taskOperateBeanList.get(position);
                if(taskOperateBean==null){
                    return new WaitToDockFragment();
                }
                return FragmentLoadUtils.loadQueseFragment(taskOperateBean);
            }

            @Override
            public int getItemCount() {
                return taskOperateBeanList.size();
            }
        });

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if(getContext()==null){
                    return;
                }
                currentTopicIndex=position;
                viewpagerContainer.setCurrentIndex(currentTopicIndex);
                IndexBean allRealIndex = getAllRealIndex();
                TaskOperateBean taskOperateBean = taskOperateBeanList.get(position);
                int kindType = taskOperateBean.getKindType();
                int typeIndex = taskOperateBean.getTypeIndex();
                int quesIndex = taskOperateBean.getQuesIndex();
                FragmentCommunicationUtils.switchTestQuesionToEvent(typeIndex,quesIndex,
                        allRealIndex.getChildIndex(),kindType==0,0);
                if(getActivity()!=null){
                    SoftInputUtils.hideSoftInput(getActivity());
                }
            }

        });
        viewPager2.setOffscreenPageLimit(1);
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        int loadTypIndex = taskControlBean.getLoadTypIndex();
        if(loadTypIndex<0){
            return;
        }
        int loadQuesIndex = taskControlBean.getLoadQuesIndex();
        int loadChildIndex = taskControlBean.getLoadChildIndex();
        int loadItemIndex = taskControlBean.getLoadItemIndex();
        taskControlBean.setLoadTypIndex(-1);
        taskControlBean.setLoadQuesIndex(-1);
        taskControlBean.setLoadChildIndex(-1);
        taskControlBean.setLoadItemIndex(-1);
        boolean loadToLead = taskControlBean.isLoadToLead();
        taskControlBean.setLoadToLead(false);
        int enableAutoPlay = taskControlBean.getEnableAutoPlay();
        if(loadTypIndex!=0){
            taskControlBean.setEnableAutoPlay(0);
        }
        IndexBean indexBean=new IndexBean();
        indexBean.setTypeIndex(loadTypIndex);
        indexBean.setQuesIndex(loadQuesIndex);
        indexBean.setChildIndex(loadChildIndex);
        indexBean.setItemIndex(loadItemIndex);
        ConstantBean.Companion.setSkipToAimIndexBean(null);
        Single.timer(0, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    taskControlBean.setEnableAutoPlay(enableAutoPlay);
                    skipToAimFragment(loadTypIndex,loadQuesIndex,loadChildIndex,loadItemIndex,loadToLead,true);
                });
    }

    /**
     * 开始下一答题作答
     */
    public void jumpNextQuese(){
        if(currentTopicIndex<taskOperateBeanList.size()-1){
            viewPager2.setCurrentItem(currentTopicIndex+1);
        }
    }

    /**
     * 跳转指定试题作答
     * @param answerSheetEvent eventBean
     * @param isNeedToLeardPage 是否需要进去导语界面
     * @param isDefaultJump 是否是默认跳转
     */
    private void jumpToAimFragment(AnswerSheetEventBean answerSheetEvent,boolean isNeedToLeardPage,boolean isDefaultJump){
        Log.e(TAG,"0726\n"+new Gson().toJson(answerSheetEvent));
        Log.e(TAG,"queseIndexMap\n"+new Gson().toJson(queseIndexMap));
        int typeIndex = answerSheetEvent.getTypeIndex();
        int quesIndex = answerSheetEvent.getQuesIndex();
        int childIndex = answerSheetEvent.getChildIndex();
        Integer topicIndex =queseIndexMap.get(typeIndex+""+quesIndex+""+childIndex);
        Log.e(TAG,"topicIndex:"+topicIndex);
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        boolean isSmoothScroll = taskControlBean.isSmoothScrollPaperFromAnswerSheet();
        if(topicIndex==null||viewPager2.getAdapter()==null||
                ConstantBean.Companion.getTaskControlBean()==null){
            return;
        }
        ExamViewBean constantExamBean = ConstantBean.Companion.getConstantExamBean();
        if(constantExamBean!=null){
            List<Type> typeList = constantExamBean.getTypeList();
            if(typeList!=null){
                Type type = typeList.get(typeIndex);
                List<Ques> quesList = type.getQuesList();
                if(quesList!=null&&quesIndex<quesList.size()&&quesIndex>=0){
                    Ques ques = quesList.get(quesIndex);
                    ques.setCurrentLoadChildIndex(childIndex);
                    List<Child> childList = ques.getChildList();
                    if(childList!=null&&childIndex<childList.size()&&childIndex>=0){
                        Child child = childList.get(childIndex);
                        child.setCurrentLoadItemIndex(answerSheetEvent.getItemIndex());
                    }
                }
            }
        }
        Log.e(TAG,"setCurrentItem:"+(topicIndex));
        if (isNeedToLeardPage && topicIndex > 0) {
            TaskOperateBean taskOperateBean = taskOperateBeanList.get(topicIndex - 1);
            int kindType = taskOperateBean.getKindType();
            if (kindType == 0) {
                Log.e(TAG,"introduction page:"+(topicIndex - 1));
                viewPager2.setCurrentItem(topicIndex - 1, isSmoothScroll&&!isDefaultJump);
                return;
            }
        }
        viewPager2.setCurrentItem(topicIndex,isSmoothScroll&&!isDefaultJump);

        long itemId = viewPager2.getAdapter().getItemId(topicIndex);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        TaskOperateBean taskOperateBean = taskOperateBeanList.get(topicIndex);
        FragmentCommunicationUtils.gotoAimFragment(fragment,answerSheetEvent,taskOperateBean);

    }

    /**
     * 外部跳转指定fragment
     * @param typeIndex  typeIndex
     * @param quesIndex quesIndex
     * @param childIndex childIndex
     * @param itemIndex itemIndex
     * @param isNeedToLeardPage 是否跳转至导语界面
     * @param isDefaultJump 是否是默认跳转
     */
    public void skipToAimFragment(int typeIndex,int quesIndex,int childIndex,int itemIndex,boolean isNeedToLeardPage,boolean isDefaultJump){
        if(ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        typeIndex=Math.max(0,typeIndex);
        quesIndex=Math.max(0,quesIndex);
        childIndex=Math.max(0,childIndex);
        itemIndex=Math.max(0,itemIndex);

        Fragment fillDialogFragment = getChildFragmentManager().findFragmentByTag(FillAnswerDialog.TAG);
        if(fillDialogFragment instanceof FillAnswerDialog){
            boolean isIgnoreJump= ((FillAnswerDialog)fillDialogFragment).forceUpdateAnswerIndex(typeIndex,quesIndex);
            if(isIgnoreJump){
                Log.e("ee","忽略此次跳转");
                return;
            }
        }
        if(ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        List<Type> typeList = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(typeList==null) {
            return;
        }
        if(typeIndex>=typeList.size()){
            return;
        }
        Type type = typeList.get(typeIndex);

        List<Ques> quesList = type.getQuesList();
        if(quesList==null||quesList.size()<=quesIndex) {
            return;
        }
        Ques ques = quesList.get(quesIndex);
        List<Child> childList = ques.getChildList();
        if(childList==null) {
            return;
        }
        int tempIndex=itemIndex;
        if(childIndex>=childList.size()){
            tempIndex=childIndex;
            childIndex=0;
        }

        Child child = childList.get(childIndex);
        String sortIndexType = child.getSortIndexType();
        if(TextUtils.equals(sortIndexType,"1")){
            itemIndex=tempIndex;
        }
        if(child.getItemList()==null) {
            return;
        }
        if(itemIndex>=child.getItemList().size()){
            itemIndex=0;
        }
        AnswerSheetEventBean answerSheetEventBean=new AnswerSheetEventBean();
        answerSheetEventBean.setTypeIndex(typeIndex);
        answerSheetEventBean.setQuesIndex(quesIndex);
        answerSheetEventBean.setChildIndex(childIndex);
        answerSheetEventBean.setItemIndex(itemIndex);
        Log.e("eeee","paperfragment jumpToAimChildFragment"+childIndex+","+itemIndex);
        jumpToAimFragment(answerSheetEventBean,isNeedToLeardPage,isDefaultJump);
    }


    /**
     * 更新小题作答倒计时样式
     * @param typeIndex 题型下标
     * @param quesIndex 大题下标
     * @param childIndex 小题小标
     * @param countdown 倒计时秒数
     * @param isShow 是否显示倒计时样式
     */
    public void updateChildAnswerCountdown(int typeIndex,int quesIndex,int childIndex,int countdown,boolean isShow){

        Integer topicIndex =queseIndexMap.get(typeIndex+""+quesIndex+""+childIndex);
        if(topicIndex==null||viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        long itemId = viewPager2.getAdapter().getItemId(topicIndex);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        FragmentCommunicationUtils.updateChildAnswerCountdown(fragment,countdown,isShow);
    }

    public void updateQuesAudioPlayState(int typeIndex,int quesIndex,boolean isPlaying){
        Integer topicIndex =queseIndexMap.get(typeIndex+""+quesIndex+""+0);
        if(topicIndex==null||viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        long itemId = viewPager2.getAdapter().getItemId(topicIndex);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        FragmentCommunicationUtils.updateQuesAudioPlayState(fragment,isPlaying);
    }

    public void closeAudioAnswerProcess(){
        FragmentCommunicationUtils.closeAudioAnswerProcess(this);
    }

    /**
     * 调整字体大小
     */
    public void adjustFontSize(){
        FragmentCommunicationUtils.adjustFontSize(this);
    }

    /**
     * 标记小题
     */
    public void markQuestion(){
        if(viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        FragmentCommunicationUtils.markQuestion(fragment);
    }

    /**
     * 外部图片作答同步
     * @param bean
     */
    public void updateImgAnswerCallBack(ImgAnswerCallBackBean bean){
        if(viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        int typeIndex = bean.getTypeIndex();
        int quesIndex = bean.getQuesIndex();
        Integer integer = queseIndexMap.get( typeIndex + "" + quesIndex+""+0);
        if(integer!=null){
            try {
                String identifyContent = bean.getIdentifyContent();
                TaskOperateBean taskOperateBean = taskOperateBeanList.get(viewPager2.getCurrentItem());
                Ques quesBean = taskOperateBean.getQuesBean();
                Item item = quesBean.getChildList().get(0).getItemList().get(bean.getItemIndex());
                long itemId = viewPager2.getAdapter().getItemId(integer);
                String imgRecognitionTxt = item.getImgRecognitionTxt();
                if(imgRecognitionTxt==null){
                    item.setImgRecognitionTxt(identifyContent);
                }else{
                    item.setImgRecognitionTxt(imgRecognitionTxt+identifyContent);
                }
                Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
                FragmentCommunicationUtils.updateImgAnswerCallBack(fragment,bean);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    /**
     * 自动播放音频
     */
    public void autoPlayAudio( ){
        if(viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        List<Fragment> fragments =getChildFragmentManager().getFragments();
        for (Fragment f:fragments){
            if(f instanceof NoSpliteLayoutFragment){
                ((NoSpliteLayoutFragment)f).onTrainStateChange();
            }
        }
        FragmentCommunicationUtils.autoPlayAudio(fragment);
    }

    /**
     * 点击答题卡序号回调
     * @param answerSheetEvent event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventMainThread(AnswerSheetEventBean answerSheetEvent) {
        if(System.currentTimeMillis()-subTime<100){
            return;
        }
        subTime=System.currentTimeMillis();
        closeAnswerSheetDialog();
        if(answerSheetEvent.getEventType()==0){
            IndexBean indexBean=new IndexBean();
            indexBean.setTypeIndex(answerSheetEvent.getTypeIndex());
            indexBean.setQuesIndex(answerSheetEvent.getQuesIndex());
            indexBean.setChildIndex(answerSheetEvent.getChildIndex());
            indexBean.setItemIndex(answerSheetEvent.getItemIndex());
            ConstantBean.Companion.setSkipToAimIndexBean(indexBean);
        }else{
            ConstantBean.Companion.setSkipToAimIndexBean(null);
        }
        jumpToAimFragment(answerSheetEvent,false,true);
    }

    /**
     * 打开答题卡
     */
    public void showAnswerSheetDialog(){
        if(System.currentTimeMillis()-subTime<200||
                viewPager2==null||viewPager2.getAdapter()==null||
                ConstantBean.Companion.getTaskControlBean()==null){
            return;
        }
        int height = viewPager2.getHeight();
        subTime=System.currentTimeMillis();
        TaskOperateBean taskOperateBean = taskOperateBeanList.get(currentTopicIndex);
        int typeIndex1 = taskOperateBean.getTypeIndex();
        int quesIndex = taskOperateBean.getQuesIndex();
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        int kindType = taskOperateBean.getKindType();
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        int childIndex= FragmentCommunicationUtils.getCurrentQuesChildIndex(fragment);
        int itemIndex= FragmentCommunicationUtils.getCurrentQuesItemIndex(fragment);
        boolean isSame=lastTypeIndex==typeIndex1&&
                lastQuesIndex==quesIndex&&
                lastChildIndex==childIndex&&
                lastItemIndex==itemIndex;
        AnswerSheetDialog.
                launchAnswerSheetDialog(PaperFragment.this.getChildFragmentManager(),
                        typeIndex1,quesIndex,childIndex,itemIndex,isSame?answerSheetScrollY:-1,height,kindType);
        lastTypeIndex=typeIndex1;
        lastQuesIndex=quesIndex;
        lastChildIndex=childIndex;
        lastItemIndex=itemIndex;
    }

    /**
     * 关闭答题卡
     */
    public void closeAnswerSheetDialog(){
        Fragment fragmentByTag = getChildFragmentManager().findFragmentByTag(AnswerSheetDialog.TAG);
        if(fragmentByTag instanceof AnswerSheetDialog){
            answerSheetScrollY=((AnswerSheetDialog)fragmentByTag).getScrollY();
            ((AnswerSheetDialog)fragmentByTag).dismissAllowingStateLoss();
        }
    }

    /**
     * 关闭所有音频播放
     */
    public void closeAllAudioPlay(){
        FragmentCommunicationUtils.closeAllMediaPlay(this);
    }

    /**
     * 获取当前Type,Ques,Child下标
     */
    public Triple<Integer,Integer,Integer> getCurrentIndex(){
        if(viewPager2==null||ConstantBean.Companion.getTaskControlBean()==null||
                viewPager2.getAdapter()==null){
            return new Triple<>(0,0,0);
        }
        TaskOperateBean taskOperateBean = taskOperateBeanList.get(currentTopicIndex);
        int typeIndex = taskOperateBean.getTypeIndex();
        int quesIndex = taskOperateBean.getQuesIndex();
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        int childIndex= FragmentCommunicationUtils.getCurrentQuesChildIndex(fragment);
        return new Triple<>(typeIndex,quesIndex,childIndex);
    }

    /**
     * 获取当前Type,Ques,Child,Item下标
     */
    public IndexBean getAllRealIndex(){
        IndexBean indexBean = new IndexBean();
        if(viewPager2==null||ConstantBean.Companion.getTaskControlBean()==null||
                viewPager2.getAdapter()==null){
            return indexBean;
        }
        TaskOperateBean taskOperateBean = taskOperateBeanList.get(currentTopicIndex);
        int typeIndex = taskOperateBean.getTypeIndex();
        int quesIndex = taskOperateBean.getQuesIndex();
        int currentItem = viewPager2.getCurrentItem();
        long itemId = viewPager2.getAdapter().getItemId(currentItem);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        int childIndex= FragmentCommunicationUtils.getCurrentQuesChildIndex(fragment);
        int itemIndex= FragmentCommunicationUtils.getCurrentQuesItemIndex(fragment);
        indexBean.setTypeIndex(typeIndex);
        indexBean.setQuesIndex(quesIndex);
        indexBean.setChildIndex(childIndex);
        indexBean.setItemIndex(itemIndex);
        indexBean.setLeadPage(taskOperateBean.getKindType()==0);
        indexBean.setCurrentPageIndex(currentTopicIndex);
        return indexBean;
    }

    @Override
    public void onGlobalLayout() {
        //获取当前根视图在屏幕上显示的大小
        if(getActivity() == null || getActivity().getWindow() == null){
            return;
        } else {
            getActivity().getWindow().getDecorView();
        }
        View decorView = getActivity().getWindow().getDecorView();
        Rect r = new Rect();
        decorView.getWindowVisibleDisplayFrame(r);
        int visibleHeight = r.height();
        System.out.println(""+visibleHeight);
        if (rootViewVisibleHeight == 0) {
            rootViewVisibleHeight = visibleHeight;
            return;
        }
        //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
        if (rootViewVisibleHeight == visibleHeight) {
            return;
        }
        //根视图显示高度变小超过200，可以看作软键盘显示了
        if (rootViewVisibleHeight - visibleHeight > 200) {
            keyBoardShow();
            rootViewVisibleHeight = visibleHeight;
            return;
        }
        //根视图显示高度变大超过200，可以看作软键盘隐藏了
        if (visibleHeight - rootViewVisibleHeight > 200) {
            keyBoardHide();
            rootViewVisibleHeight = visibleHeight;
        }
    }

    private void SoftKeyBoardListener(){
        if(convertView==null||getActivity()==null){
            return;
        }
        View decorView = getActivity().getWindow().getDecorView();
        //监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    private void keyBoardShow(){
        showKeyBoardState(true);
    }

    private void keyBoardHide(){
        if(convertView==null){
            return;
        }
        showKeyBoardState(false);
    }

    /**
     * 监听软件盘显隐
     * @param isShow 是否实现状态
     */
    private void showKeyBoardState(boolean isShow){
        if(viewPager2==null||viewPager2.getAdapter()==null){
            return;
        }
        KeyBoardEventBean keyBoardEventBean = new KeyBoardEventBean();
        keyBoardEventBean.setKeyBoardShowState(isShow?1:0);
        EventBus.getDefault().post(keyBoardEventBean);
        long itemId = viewPager2.getAdapter().getItemId(currentTopicIndex);
        Fragment fragment = getChildFragmentManager().findFragmentByTag("f"+itemId);
        FragmentCommunicationUtils.showSoftKeyBoardState(fragment,isShow);
    }

    public void disableVpScorll(){
        if(viewPager2!=null){
            viewPager2.setUserInputEnabled(false);
            Single.timer(250, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(this))
                    .subscribe(aLong ->  viewPager2.setUserInputEnabled(true));
        }

//        AlertDialog showDialog =
//                NoConfirmDialogHelper.showDialog(getContext(), "改错题暂不支持标记为\"不确定\"")
//        if(showDialog==null){
//            return;
//        }
//        Observable.timer(2000,TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .as(RxLife.as(this))
//                .subscribe(aLong -> showDialog.dismiss(), throwable -> {
//
//                });
    }

    /**
     * 最后一个小题作答完就需要触发答题卡显示
     * @param eventBean bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCompleteCurrentAnsPointEven(CompleteCurrentAnsPointEventBean eventBean){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
        boolean isAuto=taskControlBean.getIsAutoShowSubmitBtn()==1;
        if(currentTopicIndex==taskOperateBeanList.size()-1&&isAuto){
            //最后一个题了
            boolean answerForLastChild = PaperDataUtils.isAnswerForLastChild();
            if(answerForLastChild){
                showAnswerSheetDialog();
            }
        }
        Log.e("completeEvent","需要判断是否全部完成作答");
    }
}